'''日历应用,在日历上做笔记.

有2个post方法,一个是获取某一个月的记录,一个是添加某一天的记录.
名为'getMonthData'的post请求,接收的数据是{'month':形如2020-02的字符串},
  返回一个{},里面是当月的笔记资料
名为'saveData'的post请求,接收的数据是{'day':形如2020-02-03的字符串,'data':{
笔记字典}},返回{'result':'succeed'或'error'}.

getPage因为页面带参数,也要重写.页面形如:
http://127.0.0.1:5001/page/MyFlaskCalender/MyFlaskCalender.html??m=202012
指定日历的月份
'''

import sys
import os
import json

from flask import render_template

from BaseApp import BaseApp

class MyFlaskCalendar(BaseApp):

  def __init__(self):
    BaseApp.__init__(self, 'MyFlaskCalendar')
    self._jsonFilepath = os.path.join(sys.path[0], 'database',
      'Calendar.json')
    self._json = {}
    try:
      with open(self._jsonFilepath, 'rb') as f:
        self._json = json.loads(f.read().decode('utf8'))
    except:
      with open(self._jsonFilepath, 'wb') as f:
        f.write(json.dumps(self._json, ensure_ascii = False).encode('utf8'))
    return
    
  def getPage(self, page, flaskRequest):
    if '?' in page:
      page = page.split('?')[0]
    return render_template(f'{self._appname}/{page}')
    
  def postMethod(self, methodName, flaskRequest):
    if (methodName == 'getMonthData'):
      # 获取月数据
      month = flaskRequest.form['month']
      if month in self._json:
        return self._json[month]
      else:
        return {}
    if (methodName == 'save'):
      year, month ,day = flaskRequest.form['day'].split('-')
      month = year+'-'+month
      if not (month in self._json):
        self._json[month] = {}
      self._json[month][day] = {
        'title': flaskRequest.form['title'],
        'text': flaskRequest.form['text']
      }
      try:
        with open(self._jsonFilepath, 'wb') as f:
          f.write(json.dumps(self._json, ensure_ascii = False).encode('utf8'))
        return {'result':'succeed'}
      except:
        return {'result':'error'}
    return
      